package com.fs.system.college_admin.service;

import cn.hutool.core.util.ObjectUtil;
import com.fs.system.college_admin.domain.CollegeAdmin;
import com.fs.system.college_admin.domain.End;
import com.fs.system.college_admin.domain.Given;
import com.fs.system.college_admin.mapper.ActiveCreditMapper;
import com.fs.system.college_admin.mapper.ActiveTypeMapper;
import com.fs.system.college_admin.mapper.CollegeAdminMapper;
import com.fs.system.exception.CustomerException;
import com.fs.system.manager.domain.Account;
import com.fs.system.manager.service.MessageService;
import com.fs.system.student.domain.ActCredit;
import com.fs.system.student.domain.ApplicationRecord;
import com.fs.system.student.mapper.StudentMapper;
import com.fs.system.teacher.domain.First;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class CollegeAdminService {

    @Resource
    private CollegeAdminMapper collegeAdminMapper;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    ActiveTypeMapper activeTypeMapper;

    @Autowired
    ActiveCreditMapper activeCreditMapper;

    @Autowired
    private MessageService messageService;

    public void addCollegeAdmin(CollegeAdmin collegeAdmin) {
        CollegeAdmin dbCollegeAdmin = collegeAdminMapper.selectByUsername(collegeAdmin.getUsername());
        if(Objects.nonNull(dbCollegeAdmin)){
            throw new CustomerException("500","新增失败！用户名已存在");
        }
        collegeAdmin.setPassword(collegeAdmin.getUsername());  //默认密码和用户名一致
        collegeAdmin.setDeleted(false);
        collegeAdmin.setCreateTime(LocalDateTime.now());
        collegeAdminMapper.addOne(collegeAdmin);
    }

    public List<CollegeAdmin> getCollegeAdminList(CollegeAdmin collegeAdmin) {
        return collegeAdminMapper.selectAll(collegeAdmin);
    }

    public PageInfo<CollegeAdmin> selectPage(CollegeAdmin collegeAdmin, Integer pageNum, Integer pageSize) {
        //开启分页查询（传参：当前页码、每页分页个数）
        PageHelper.startPage(pageNum,pageSize);
        //查询所有的数据
        List<CollegeAdmin> collegeAdminList = collegeAdminMapper.selectAll(collegeAdmin);
        //PageInfo执行分页操作
        return PageInfo.of(collegeAdminList);
    }

    public void updateCollegeAdmin(CollegeAdmin collegeAdmin) {
        Long adminIdUpdate = collegeAdmin.getAdminId();
        String usernameUpdate = collegeAdmin.getUsername();
        CollegeAdmin dbCollegeAdmin = collegeAdminMapper.selectCollegeAdminById(adminIdUpdate);
        if (!dbCollegeAdmin.getUsername().equals(usernameUpdate)) {
            CollegeAdmin dbCollegeAdmin02 = collegeAdminMapper.selectByUsername(usernameUpdate);
            if (Objects.nonNull(dbCollegeAdmin02)) {
                throw new CustomerException("500", "更新失败！用户名已存在");
            }
        }
        /*collegeAdmin.setUpdateBy(collegeAdmin.getUsername());*/
        collegeAdmin.setUpdateTime(LocalDateTime.now());
        collegeAdminMapper.update(collegeAdmin);
    }

    public void deleteCollegeAdmin(Long adminId, String updateBy) {
        CollegeAdmin dbCollegeAdmin = collegeAdminMapper.selectCollegeAdminById(adminId);
        if(Objects.isNull(dbCollegeAdmin)){
            throw new CustomerException("500","删除失败");
        }
        dbCollegeAdmin.setDeleted(true);
        dbCollegeAdmin.setUpdateBy(updateBy);
        dbCollegeAdmin.setUpdateTime(LocalDateTime.now());
        collegeAdminMapper.update(dbCollegeAdmin);
    }

    public void deleteBatch(List<Long> ids, String updateBy) {
        for (Long adminId :ids) {
            this.deleteCollegeAdmin(adminId, updateBy);
        }
    }

    /**
     * 院管理员登录
     * @param account
     * @return
     */
    public Map<String, Object> login(Account account) {
        Map<String, Object> resMap = new HashMap<>();
        CollegeAdmin dbCollegeAdmin = collegeAdminMapper.selectByUsername(account.getUsername());
        if(Objects.isNull(dbCollegeAdmin)){
            throw new CustomerException("500","用户名不存在");
        }
        if(!"0".equals(dbCollegeAdmin.getStatus())){
            throw new CustomerException("500","用户状态不合法");
        }
        //用户存在
        //判断密码是否正确
        if(!dbCollegeAdmin.getPassword().equals(account.getPassword())){
            throw new CustomerException("500","用户名或密码错误");
        }
        //所有逻辑判断没有问题，返回前端所需
        resMap.put("adminId", dbCollegeAdmin.getAdminId());
        resMap.put("username", dbCollegeAdmin.getUsername());
        resMap.put("nickname", dbCollegeAdmin.getNickname());
        resMap.put("collegeId", dbCollegeAdmin.getCollegeId());
        resMap.put("collegeName", dbCollegeAdmin.getCollegeName());
        resMap.put("status", dbCollegeAdmin.getStatus());
        resMap.put("role", dbCollegeAdmin.getRole());
        return resMap;
    }

    /**
     * 修改密码
     * @param account
     */
    public void updatePassword(Account account) {
        /*从数据库拿出对象*/
        CollegeAdmin dbCollegeAdmin = collegeAdminMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbCollegeAdmin)) {
            throw new CustomerException("500","用户不存在");
        }
        /*判断原本输入传过来的原密码和查到的用户在数据库的密码是否一致*/
        if (!account.getPassword().equals(dbCollegeAdmin.getPassword())) {
            throw new CustomerException("500","原密码错误");
        }
        dbCollegeAdmin.setPassword(account.getNewPassword());
        dbCollegeAdmin.setUpdateBy(account.getUsername());
        dbCollegeAdmin.setUpdateTime(LocalDateTime.now());
        /*将更新过的对象再更新到数据库里面*/
        collegeAdminMapper.update(dbCollegeAdmin);
    }

    /**
     * 根据teaId查询记录列表
     * @param teaList
     * @param page
     * @param size
     * @return
     */
    public PageInfo<ApplicationRecord> getEnd(List<Integer> teaList, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        // 用于存储所有教师的申请记录
        List<ApplicationRecord> allRecords = new ArrayList<>();
        // 遍历每个教师ID，查询其申请记录并添加到总列表
        for (Integer teaId : teaList) {
            List<ApplicationRecord> teacherRecords = collegeAdminMapper.selectEnd(teaId);
            for(ApplicationRecord a:teacherRecords){
                a.setStuName(studentMapper.selectStudentById(a.getStuId()).getRealname());
                a.setTypeName(activeTypeMapper.selectActiveTypeById(a.getTypeId()).getName());
                a.setActName(activeCreditMapper.selectActiveCreditById(a.getActId()).getActName());
            }
            if (teacherRecords != null && !teacherRecords.isEmpty()) {
                allRecords.addAll(teacherRecords);
            }
        }
        return PageInfo.of(allRecords);

    }

    /**
     * 查询一周前的记录
     * @param teaList
     * @param page
     * @param size
     * @return
     */
    public PageInfo<ApplicationRecord> getEnd2(List<Integer> teaList, Integer page, Integer size) {
        PageHelper.startPage(page,size);

        // 用于存储所有教师的申请记录
        List<ApplicationRecord> allRecords = new ArrayList<>();
        // 遍历每个教师ID，查询其申请记录并添加到总列表
        for (Integer teaId : teaList) {
            List<ApplicationRecord> teacherRecords = collegeAdminMapper.selectEnd2(teaId);
            for(ApplicationRecord a:teacherRecords){
                a.setStuName(studentMapper.selectStudentById(a.getStuId()).getRealname());
                a.setTypeName(activeTypeMapper.selectActiveTypeById(a.getTypeId()).getName());
                a.setActName(activeCreditMapper.selectActiveCreditById(a.getActId()).getActName());
            }
            if (teacherRecords != null && !teacherRecords.isEmpty()) {
                allRecords.addAll(teacherRecords);
            }
        }
        return PageInfo.of(allRecords);

    }

    /**
     * 院长终审材料
     * @param applicationRecord
     */
    public void endCheck(ApplicationRecord applicationRecord) {
        collegeAdminMapper.endUpdate(applicationRecord);
        //如果为操作为通过，则为学生加上对应的学分
        ApplicationRecord co = collegeAdminMapper.selectRecordById(applicationRecord);
        if(co.getStatus().equals("0")){
            studentMapper.addCredit(co.getCreditCount(),co.getStuId());
        }
    }

    /**
     * 添加终审记录
     * @param end
     */
    public void endRecord(End end) {
        end.setCreateTime(LocalDateTime.now());
        collegeAdminMapper.endRecord(end);
    }

    //院长查看终审记录
    public PageInfo<End> getRecord(End end, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<End> list = collegeAdminMapper.selectRecord(end);
        return PageInfo.of(list);
    }

    /**
     * 根据记录id查询信息
     * @param end
     * @param page
     * @param size
     * @return
     */
    public ApplicationRecord getRecordById(End end, Integer page, Integer size) {
        ApplicationRecord record = collegeAdminMapper.getRecordById(end.getRecordId());
        record.setStuName(studentMapper.selectStudentById(record.getStuId()).getRealname());
        record.setTypeName(activeTypeMapper.selectActiveTypeById(record.getTypeId()).getName());
        record.setActName(activeCreditMapper.selectActiveCreditById(record.getActId()).getActName());
        return record;
    }

    //院长查看分配记录
    public PageInfo<Given> getGivenRecord(Given given, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<Given> list = collegeAdminMapper.selectGivenRecord(given);
        return PageInfo.of(list);
    }

    /**
     *根据记录id查询已分配的信息
     * @param given
     * @param page
     * @param size
     * @return
     */
    public ApplicationRecord getGivenById(Given given, Integer page, Integer size) {
        ApplicationRecord record = collegeAdminMapper.getRecordById(given.getRecordId());
        record.setStuName(studentMapper.selectStudentById(record.getStuId()).getRealname());
        record.setTypeName(activeTypeMapper.selectActiveTypeById(record.getTypeId()).getName());
        record.setActName(activeCreditMapper.selectActiveCreditById(record.getActId()).getActName());
        return record;
    }
}
